var directions = [],
    lastPressTime, stepped, ti, frameRate = 30,
    squareSpeed = 5, stepTime = 100;

function update() {
    var x, y, d = directions[directions.length - 1],
        square = document.getElementById('square');
    if (!d) {
        return;
    }
    if (new Date().getTime() < lastPressTime + stepTime) {
        if (stepped) {
            return;
        }
        else {
            stepped = true;
        }
    }
    if (d == 'left') {
        square.style.left = square.offsetLeft - squareSpeed + 'px';
    }
    else if (d == 'right') {
        square.style.left = square.offsetLeft + squareSpeed + 'px';
    }
    else if (d == 'up') {
        square.style.top = square.offsetTop - squareSpeed + 'px';
    }
    else if (d == 'down') {
        square.style.top = square.offsetTop + squareSpeed + 'px';
    }
}

function checkArrowKeys(e) {
    var arrs = [],
        key = window.event ? event.keyCode : e.keyCode;
    arrs[37] = 'left';
    arrs[38] = 'up';
    arrs[39] = 'right';
    arrs[40] = 'down';
    if (arrs[key]) {
        return arrs[key];
    }
}
document.onkeydown = function(e) {
    var d = checkArrowKeys(e);
    if (d) {
        if (directions.indexOf(d) === -1) {
            directions.push(d);
            lastPressTime = new Date().getTime();
            stepped = false;
        }
        if (!ti) {
            ti = setInterval(update, 1000 / frameRate);
        }
    }
};

document.onkeyup = function(e) {
    var d = checkArrowKeys(e),
        i;
    if (d) {
        i = directions.indexOf(d);
        if (i > -1) {
            directions = directions.slice(0, i).concat(directions.slice(i + 1));
        }
        if (directions.length === 0) {
            clearInterval(ti);
            ti = null;
        }
    }
};